package com.zxy.controlcenter.core.shiro;

import com.alibaba.fastjson.JSONObject;
import com.zxy.controlcenter.core.shiro.service.UserAuthService;
import com.zxy.controlcenter.core.shiro.service.impl.UserAuthServiceImpl;
import com.zxy.controlcenter.modular.system.model.Admin;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @author zxy
 */
@Slf4j
public class ShiroDbRealm extends AuthorizingRealm {

    /**
     * 权限认证
     *
     * @param principalCollection 权限凭证
     * @return 权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 登录认证
     *
     * @param authcToken 凭证token
     * @return 凭证信息
     * @throws AuthenticationException 异常错误
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        log.info("登录凭证authcToken:{}", JSONObject.toJSONString(authcToken));
        UserAuthService shiroFactory = UserAuthServiceImpl.me();
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        Admin admin = shiroFactory.getAdminByAccount(token.getUsername());
        ShiroUser shiroUser = shiroFactory.getShiroAdmin(admin);
        return shiroFactory.info(shiroUser, admin, getName());
    }

    /**
     * 加密算法
     *
     * @param credentialsMatcher 凭证匹配规则
     */
    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher md5CredentialsMatcher = new HashedCredentialsMatcher();
        md5CredentialsMatcher.setHashAlgorithmName(ShiroKit.HASH_ALGORITHM_NAME);
        md5CredentialsMatcher.setHashIterations(ShiroKit.HASH_ITERATIONS);
        super.setCredentialsMatcher(md5CredentialsMatcher);
    }

    public static void main(String[] args) {
        // TODO 密码MD5加密测试
        String hashAlgorithmName = "MD5";
        String credentials = "123456";
        int hashIterations = 1024;
        ByteSource credentialsSalt = new Md5Hash("e2r5dw");
        Object obj = new SimpleHash(hashAlgorithmName, credentials, credentialsSalt, hashIterations);
        System.out.println(obj);
    }
}
